import requests
import time
import os

class VirusTotalCollector:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://www.virustotal.com/api/v3/"
        
    def _make_request(self, endpoint):
        headers = {"x-apikey": self.api_key}
        response = requests.get(f"{self.base_url}{endpoint}", headers=headers)
        return response.json()

    def download_samples(self, query, save_dir, limit=100):
        """下载恶意软件样本"""
        samples = self._make_request(f"intelligence/search?query={query}&limit={limit}")
        os.makedirs(save_dir, exist_ok=True)
        
        for sample in samples.get('data', []):
            sample_id = sample['id']
            file_path = os.path.join(save_dir, f"{sample_id}.bin")
            response = self._make_request(f"files/{sample_id}/download")
            
            if response.get('data'):
                with open(file_path, 'wb') as f:
                    f.write(response['data'])
                print(f"Downloaded: {file_path}")
                time.sleep(15)  # 遵守API速率限制 